package com.company.controller;

import com.company.mapper.EmployeeMapper;
import com.company.model.Employee;
import com.company.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/employee/edit")
public class EditEmployeeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1. 获取要编辑的员工ID
        int id = Integer.parseInt(request.getParameter("id"));

        // 2. 调用MyBatis查询员工信息
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        Employee employee = employeeMapper.getEmployeeById(id); // 调用MyBatis的Mapper接口
        MyBatisUtil.closeSqlSession(sqlSession);

        // 3. 传递员工信息到编辑页面
        if (employee != null) {
            request.setAttribute("employee", employee);
            request.getRequestDispatcher("/WEB-INF/jsp/employee/edit.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/employee/list?error=员工不存在");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        // 1. 获取表单提交的员工信息
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String department = request.getParameter("department");
        String position = request.getParameter("position");
        BigDecimal salary = new BigDecimal(request.getParameter("salary"));
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String hireDateStr = request.getParameter("hireDate");

        // 2. 转换日期格式
        Date hireDate = null;
        try {
            hireDate = new SimpleDateFormat("yyyy-MM-dd").parse(hireDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("error", "日期格式错误");
            request.setAttribute("employee", getEmployeeFromRequest(request)); // 回显表单数据
            request.getRequestDispatcher("/WEB-INF/jsp/employee/edit.jsp").forward(request, response);
            return;
        }

        // 3. 封装员工对象
        Employee employee = new Employee();
        employee.setId(id);
        employee.setName(name);
        employee.setDepartment(department);
        employee.setPosition(position);
        employee.setSalary(salary);
        employee.setEmail(email);
        employee.setPhone(phone);
        employee.setHireDate(hireDate);

        // 4. 调用MyBatis执行更新操作
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        employeeMapper.updateEmployee(employee); // 调用MyBatis的Mapper接口
        MyBatisUtil.closeSqlSession(sqlSession);

        // 5. 重定向回列表页并提示结果
        response.sendRedirect(request.getContextPath() + "/employee/list?message=更新成功");
    }

    // 辅助方法：从请求中获取员工数据（用于日期格式错误时回显）
    private Employee getEmployeeFromRequest(HttpServletRequest request) {
        Employee emp = new Employee();
        emp.setId(Integer.parseInt(request.getParameter("id")));
        emp.setName(request.getParameter("name"));
        emp.setDepartment(request.getParameter("department"));
        emp.setPosition(request.getParameter("position"));
        emp.setSalary(new BigDecimal(request.getParameter("salary")));
        emp.setEmail(request.getParameter("email"));
        emp.setPhone(request.getParameter("phone"));
        return emp;
    }
}